import{ defineStore }from'pinia'
import type { ToastOptions } from'wot-design-uni/components/wd-toast/types'
import { getCurrentPath, merge } from "@/utils"

interface GlobalLoading {
  loadingOptions:ToastOptions
  currentPage:string
  currentKey: number
}

const defaultOptions: ToastOptions = {
  iconName: 'loading',
  duration: 0,
  cover: true,
  position: 'middle',
  show: false,
}

export const useGlobalLoading = defineStore('global-loading', {
  state: (): GlobalLoading =>({
    loadingOptions: defaultOptions,
    currentPage:'',
    currentKey: 0
  }),
  actions: {
    loading(option: ToastOptions | string) {
      // @ts-ignore
      this.currentPage = getCurrentPath()
      const options = merge(
        defaultOptions,
        typeof option ==='string'? {msg: option } : option
      ) as ToastOptions
      this.loadingOptions = merge(options, {
        show:true,
        position: options.position || 'middle',
      }) as ToastOptions
      this.currentKey++;
    },

    // 关闭 Toast
    close() {
      this.loadingOptions = defaultOptions
      this.currentPage = ''
      this.currentKey = -1;
    },
  },
})

export declare type LoadingUtil = ReturnType<typeof useGlobalLoading>